package com.delio.client.pagos.aportes;

import java.util.ArrayList;
import java.util.List;

import com.delio.client.idioma.DelioConstants;
import com.delio.client.idioma.DelioMessages;
import com.delio.client.util.Utilities;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.Style.SortDir;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelFactory;
import com.extjs.gxt.ui.client.data.BeanModelLookup;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.FieldEvent;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.Record;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.Radio;
import com.extjs.gxt.ui.client.widget.form.RadioGroup;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.EditorGrid;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;

public class PanelGridAporte  extends ContentPanel{
	private DelioMessages msg = GWT.create(DelioMessages.class);
	private DelioConstants k = GWT.create(DelioConstants.class);
	
	private Button btnDelete = new Button(k.eliminar(),IconHelper.createPath("images/icons/delete.gif"));
	private Button btnAdd = new Button(k.agregar(),IconHelper.createPath("images/icons/add.png"));
	private static Button btnRegistrar;
	private static Button btnCancelar;
	
	private Integer selectedSize;
	private BeanModel selectedModel;
	
	private List<BeanModel> selectedModels;
	private List<ColumnConfig> configs;
	
	private ColumnConfig column;
	private ColumnModel cm;
	
	public static EditorGrid<BeanModel> grid;
	public static TextField<String> txtCargo;
	private static NumberField txtPorcentaje;
	private final CheckBoxSelectionModel<BeanModel> sm = new CheckBoxSelectionModel<BeanModel>();
	private ToolBar toolBar = new ToolBar();
	
	private Radio rbEmpleado;
	private Radio rbEmpleador;
	

	public PanelGridAporte() {
		super();
		setHeaderVisible(false);
		setFrame(true);
		setBodyBorder(false);
		setLayout(new FitLayout());
		
		Aportes.tipoaporte_id = 1;

		rbEmpleado = new Radio();
		rbEmpleado.setValue(true);
		rbEmpleado.setBoxLabel("Empleado");

		rbEmpleador = new Radio();
		rbEmpleador.setBoxLabel("Empleador");

		RadioGroup radioGroup = new RadioGroup();
		radioGroup.add(rbEmpleado);
		radioGroup.add(rbEmpleador);
		radioGroup.addListener(Events.Change, new Listener<FieldEvent>() {
			@Override
			public void handleEvent(FieldEvent be) {

				if (rbEmpleado.getValue()) {
					Aportes.tipoaporte_id = 1;
					Aportes.loader.load();
				} else if (rbEmpleador.getValue()) {
					Aportes.tipoaporte_id = 2;
					Aportes.loader.load();

				}
			}
		});
		
		
		
		configs = new ArrayList<ColumnConfig>();

		sm.setSelectionMode(SelectionMode.SINGLE);
		
		column = new ColumnConfig();
		column.setId("nombre");
		column.setHeader(k.aporte());
		column.setWidth(200);

		txtCargo = new TextField<String>();
		txtCargo.setAllowBlank(false);
		column.setEditor(new CellEditor(txtCargo));
		configs.add(column);
		
		
		column = new ColumnConfig();
		column.setId("porcentaje");
		column.setHeader(k.porcentaje());
		column.setWidth(100);

		txtPorcentaje = new NumberField();
		txtPorcentaje.setPropertyEditorType(Double.class);
		txtCargo.setAllowBlank(false);
		column.setEditor(new CellEditor(txtPorcentaje));
		configs.add(column);
		
		
		
		configs.add(sm.getColumn());
		cm = new ColumnModel(configs);

		Aportes.getAportes();
		grid = new EditorGrid<BeanModel>(Aportes.store, cm);
		grid.setAutoExpandColumn("nombre");
		grid.setBorders(true);
		grid.setSelectionModel(sm);
		grid.addPlugin(sm);  
		grid.addListener(Events.Attach, new Listener<GridEvent<BeanModel>>() {
			@Override
			public void handleEvent(GridEvent<BeanModel> be) {
				Aportes.loader.load();

			}
		});
		grid.getSelectionModel().addListener(Events.SelectionChange,
				new Listener<SelectionChangedEvent<BeanModel>>() {

					@Override
					public void handleEvent(SelectionChangedEvent<BeanModel> be) {
						selectedSize = be.getSelection().size();

						if (selectedSize == 0) {
							btnDelete.setEnabled(false);
						} else if (selectedSize == 1) {
							selectedModel = be.getSelectedItem();
							btnDelete.setEnabled(true);
						} else if (selectedSize > 1) {
							selectedModels = be.getSelection();
							btnDelete.setEnabled(true);
						}

					}

				});

		txtCargo.addListener(Events.Detach, new Listener<BaseEvent>() {
			@Override
			public void handleEvent(BaseEvent be) {
				if (txtCargo.getValue() == null) {
					if (Aportes.store.getSortDir().equals(SortDir.ASC)|| Aportes.store.getSortDir().equals(SortDir.NONE))
						grid.getStore().remove(grid.getStore().getAt(0));
					else if (Aportes.store.getSortDir().equals(SortDir.DESC)|| Aportes.store.getSortDir().equals(SortDir.NONE))
						grid.getStore().remove(grid.getStore().getAt(grid.getStore().getCount() - 1));

					btnRegistrar.setEnabled(false);

				} else if (txtCargo.getValue() != null || txtPorcentaje.getValue() != null)
					btnRegistrar.setEnabled(true);
			}
		});

		
		
		txtPorcentaje.addListener(Events.Detach, new Listener<BaseEvent>() {
			@Override
			public void handleEvent(BaseEvent be) {
				if (txtPorcentaje.getValue() == null) {
					if (Aportes.store.getSortDir().equals(SortDir.ASC)|| Aportes.store.getSortDir().equals(SortDir.NONE))
						grid.getStore().remove(grid.getStore().getAt(0));
					else if (Aportes.store.getSortDir().equals(SortDir.DESC)|| Aportes.store.getSortDir().equals(SortDir.NONE))
						grid.getStore().remove(grid.getStore().getAt(grid.getStore().getCount() - 1));

					btnRegistrar.setEnabled(false);

				} else if (txtPorcentaje.getValue() != null)
					btnRegistrar.setEnabled(true);
			}
		});
		
		
		
		btnCancelar = new Button(k.cancelar(),IconHelper.createPath("images/icons/cancel.png"),new SelectionListener<ButtonEvent>() {

					@Override
					public void componentSelected(ButtonEvent ce) {
									Aportes.store.rejectChanges();

					}
				});
		
		btnRegistrar = new Button(k.registrar(),IconHelper.createPath("images/icons/save_all.png"),new SelectionListener<ButtonEvent>() {

					@Override
					public void componentSelected(ButtonEvent ce) {
						List<Record> re = Aportes.store.getModifiedRecords();
						for (Record r : re) {
							Aporte ti = new Aporte();
							ti.setNombre(String.valueOf(r.get("nombre")));
							ti.setPorcentaje((Double)(r.get("porcentaje")));

							if (r.get("id") != null)
								ti.setId(r.get("id").hashCode());
							Aportes.save(ti);
						}

						Aportes.store.commitChanges();
						btnRegistrar.setEnabled(false);
					}
				});
		btnAdd.addSelectionListener(new SelectionListener<ButtonEvent>() {
			@Override
			public void componentSelected(ButtonEvent ce) {
				Aporte ti = new Aporte();
				ti.setNombre("");
				ti.setPorcentaje(0.0);
		
				BeanModelFactory beanModelFactory =  BeanModelLookup.get().getFactory(ti.getClass());
				grid.stopEditing();
		
				Aportes.store.insert(beanModelFactory.createModel(ti), 0);
				grid.startEditing(Aportes.store.indexOf(beanModelFactory.createModel(ti)), 0);

			}
		});
		btnDelete.setEnabled(false);
		final Listener<MessageBoxEvent> listener = new Listener<MessageBoxEvent>() {
			@Override
			public void handleEvent(MessageBoxEvent ce) {
				String button_id = ce.getButtonClicked().getItemId();
				if (Dialog.YES == button_id) {

					if (selectedSize == 1) {
						Integer id = selectedModel.get("id");
						Aportes.delete(id);
					} else if (selectedSize > 1) {
						String ids = Utilities.toIds(selectedModels);
						Aportes.deleteAll(ids);
					}
				}
			}
		};

		SelectionListener<ButtonEvent> sl_delete;
		sl_delete = new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				String mensaje = "";
				if (selectedSize == 1) {
					String nombres = selectedModel.get("nombre");
					mensaje = msg.empleadoEstaSeguro(nombres);
				} else if (selectedSize > 1) {
					mensaje = k.eliminarAll();
				}
				MessageBox.confirm(k.confirmacion(), mensaje, listener)
						.getDialog().getButtonById(Dialog.YES)
						.setText(k.si());

			}

		};
		btnDelete.addSelectionListener(sl_delete);
//		btnCancelar.addSelectionListener(new SelectionListener<ButtonEvent>() {
//			
//			@Override
//			public void componentSelected(ButtonEvent ce) {
//			hide();
//				
//			}
//		});

		addButton(btnRegistrar);
		addButton(btnCancelar);

		toolBar.add(btnAdd);
		toolBar.add(btnDelete);
		toolBar.add(new SeparatorToolItem());
		toolBar.add(radioGroup);

		setTopComponent(toolBar);

		btnRegistrar.setEnabled(false);
		setButtonAlign(HorizontalAlignment.CENTER);
		add(grid);

	}
}
